<?php
/**
 * @file
 */
/**
 * Form filter for visitors page
 */
function chatroom_livesupport_visitors_filter_form($form, &$form_state) {
  $filters = !empty($_SESSION['chatroom_livesupport_visitors_filter']) ? $_SESSION['chatroom_livesupport_visitors_filter'] : array();
  $form['text'] = array(
    '#type' => 'markup',
    '#markup' => t('This page displays a list of visitors who are waiting. To answer the visitor click their name in the list.')
  );
  $form['filter'] = array(
    '#type' => 'fieldset',
    '#title' => t('Filters'),
    '#collapsible' => TRUE,
    '#collapsed' => !empty($filters) ? FALSE : TRUE
  );
  $form['filter']['name'] = array(
    '#type' => 'textfield',
    '#title' => t('Visistor Name'),
    '#size' => 20,
    '#autocomplete_path' => 'user/autocomplete',
    '#default_value' => !empty($filters['name']) ? $filters['name'] : '',
    '#description' => t('Enter visitor name')
  );
  $form['filter']['status'] = array(
    '#type' => 'select',
    '#title' => t('Chatroom status'),
    '#options' => array('' => t('Choose status')),
    '#default_value' => !empty($filters['status']) ? $filters['status'] : '',
  );
  $form['filter']['status']['#options'] += chatroom_livesupport_chatroom_states();
  
  $form['filter']['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Filter'),
    '#submit' => array('chatroom_livesupport_visitors_filter_form_submit')
  );
  if (!empty($filters)) {
    $form['filter']['reset'] = array(
    '#type' => 'submit',
    '#value' => t('Reset'),
    '#submit' => array('chatroom_livesupport_visitors_filter_form_submit')
  );
  }
  $form['operations'] = array(
    '#type' => 'fieldset',
    '#title' => t('Update options'),
    '#collapsible' => TRUE,
    '#collapsed' => TRUE
  );
  $form['operations']['state'] = array(
    '#type' => 'select',
    '#options' => array('' => t('Choose status')),
  );
  $form['operations']['state']['#options'] += chatroom_livesupport_chatroom_states();

  $form['operations']['update'] = array(
    '#type' => 'submit',
    '#value' => t('Update'),
    '#submit' => array('chatroom_livesupport_visitors_update')
  );
  return $form;
}

/**
 * Submit callback: lcss_operators_operations_form
 */
function chatroom_livesupport_visitors_filter_form_submit($form, &$form_state) {
  $values = $form_state['values'];
  switch($values['op']) {
    case t('Filter'):
      if (!empty($values['name'])) {
        $account = user_load_by_name($values['name']);
        if ($account) {
          $_SESSION['chatroom_livesupport_visitors_filter']['name'] = $values['name'];
        }
      }
      if (!empty($values['status'])) {
        $_SESSION['chatroom_livesupport_visitors_filter']['status'] = $values['status'];
      }
      break;
    case t('Reset'):
      $_SESSION['chatroom_livesupport_visitors_filter'] = array();
      break;
  }
}

/**
 * Submit callback: chatroom_livesupport_visitors_update
 */
function chatroom_livesupport_visitors_update($form, &$form_state) {
  $values = $form_state['values'];
  if (!empty($values['visitors'])) {
    if (!empty($values['state'])) {
      db_update('chatroom')
        ->fields(array('status' => $values['state']))
        ->condition('cid', array_values($values['visitors']))
        ->execute();
      drupal_set_message(t('Some chatrooms has been closed successful'));

      foreach ($values['visitors'] as $cid) {
        $chatroom = new ChatroomLivesupport($cid);
        if ($chatroom->get('cid')) {
          chatroom_livesupport_nodejs_update_chatroom($chatroom);
        }
      }
    }
    else {
      drupal_set_message(t('Please choose operation'), 'error');
    }
  }
  else {
    drupal_set_message(t('Please choose chatrooms'), 'error');
  }
}

/**
 * Menu callback: management visitors
 */
function chatroom_livesupport_visitors_form($form, &$form_state) {
  global $user;
  $_GET['q'] = str_replace('/update', '', $_GET['q']);
  // include filter form
  $form = chatroom_livesupport_visitors_filter_form($form, $form_state);
  $filters = !empty($_SESSION['chatroom_livesupport_visitors_filter']) ? $_SESSION['chatroom_livesupport_visitors_filter'] : array();

  $header = array(
    'username' => array('data' => t('Visitor Name'), 'field' => 'u.name'),
    'status' => array('data' => t('Status')),
    'state' => array('data' => t('State'), 'field' => 'c.status', 'sort' => 'desc'),
    'modified' => array('data' => t('Total time'), 'field' => 'c.modified', 'sort' => 'desc'),
    'joined' => array('data' => t('Waiting time'), 'field' => 'joined', 'sort' => 'desc'),
    'operator' => array('data' => t('Latest Operator'), 'field' => 'operator', 'sort' => 'desc'),
    'operations' => array('data' => t('Operations')),
  );

  $query = db_select('chatroom', 'c');

  $count_query = clone $query;
  $count_query->addExpression('COUNT(c.uid)');

  $query->innerJoin('users', 'u', 'u.uid = c.uid');
  $query->leftJoin('chatroom_user', 'cu', 'cu.uid = c.uid AND cu.cid = c.cid');
  $query->fields('c', array('cid', 'title', 'status', 'modified'));
  $query->fields('u', array('uid', 'name', 'access'));
  $query->addField('cu', 'modified', 'joined');
  $query->addExpression("(SELECT cu2.uid FROM {chatroom_user} cu2
    INNER JOIN {chatroom_operator} co ON cu2.uid = co.uid
    LEFT JOIN {users} AS u ON u.uid = cu2.uid
    WHERE c.cid = cu2.cid ORDER BY modified DESC LIMIT 1)", 'operator');

  $query->condition('u.uid', 0, '<>');

  if (!empty($filters['name'])) {
    $query->condition('u.name', $filters['name'], 'LIKE');
  }
  
  if (!empty($filters['status'])) {
    $query->condition('c.status', $filters['status']);
  }

  if (!user_access('administer chatroom_livesupport')) {
    $query->condition('c.status', array(CHATROOM_IN_CHAT, CHATROOM_WAITING, CHATROOM_IN_QUEUE), 'IN');
  }

  $query = $query->extend('PagerDefault')->limit(20)->extend('TableSort');
  $query->limit(20)
    ->orderByHeader($header)
    ->setCountQuery($count_query);
  $result = $query->execute();

  $options = array();
  foreach ($result as $chatroom) {
    $operator = NULL;
    if ($chatroom->operator) {
      $operator = user_load($chatroom->operator);
    }
    $options[$chatroom->cid] = array(
      'username' => theme('username', array('account' => $chatroom)),
      'status' =>  chatroom_livesupport_is_online_user($chatroom->uid) ? t('Online') : t('Offline'),
      'state' => chatroom_livesupport_chatroom_states($chatroom->status),
      'modified' => format_interval(REQUEST_TIME - $chatroom->modified),
      'joined' => format_interval(REQUEST_TIME - $chatroom->joined),
      'operator' => $operator ? theme('username', array('account' => $operator)) : '-',
    );
    
    $options[$chatroom->cid]['operations'] = chatroom_livesupport_chatroom_operations($chatroom);
  }

  $form['visitors'] = array(
    '#type' => 'tableselect',
    '#header' => $header,
    '#options' => $options,
    '#empty' => t('No visitor available.'),
  );

  $form['pager'] = array('#markup' => theme('pager'));

  return $form;
}

/**
 * Function helper for visitors page
 */
function chatroom_livesupport_chatroom_operations($chatroom) {
  global $user;
  $items = array();
  $items[] = array(
    'data' => l(t('Watch'), 'livesupport/watch/' . $chatroom->cid, array(
      'absolute' => TRUE, 
      'attributes' => array('target' => '_bank', 'title' => t('Watch'))        
    )),
    'class' => array('action-watch')
  );
  if (chatroom_livesupport_user_is_operator($user->uid)) {
    if ($chatroom->operator == $user->uid && $chatroom->status == CHATROOM_IN_CHAT) {
      $items[] = array(
        'data' => l(t('Leave'), 'livesupport/leave/' . $chatroom->cid, array(
          'absolute' => TRUE,
          'attributes' => array('class'=> array('use-ajax'), 'title' => t('Leave'))
        )),
        'class' => array('action-leave')
      );
      $items[] = array('data' => '<a href="#" title="' .t('Chat') . '">' . t('Chat') . '</a>', 'class' => array('action-chat'), 'id' => 'chatroom-cid-' . $chatroom->cid);
    }
    else if ($chatroom->status == CHATROOM_IN_QUEUE || $chatroom->status == CHATROOM_WAITING) {
      $items[] = array(
        'data' => l(t('Join'), 'livesupport/join/' . $chatroom->cid, array(
          'absolute' => TRUE,
          'attributes' => array('class'=> array('use-ajax'), 'title' => t('Join'))
        )),
        'class' => array('action-join')
      );
    }
    if ($chatroom->status != CHATROOM_CLOSED) {
      $items[] = array(
        'data' => l(t('Close'), 'livesupport/close/' . $chatroom->cid, array(
          'absolute' => TRUE,
          'attributes' => array('class'=> array('use-ajax'), 'title' => t('Close'))
        )),
        'class' => array('action-close')
      );
    }
  }
  return theme('item_list', array('items' => $items, 'attributes' => array('class' => array('chatroom-operations visitor-operations'))));
}

/**
 * Menu callback: Update visitors page
 */
function chatroom_livesupport_update_visitors_page() {
  $elements = drupal_get_form('chatroom_livesupport_visitors_form');
  $replace = drupal_render($elements);
  drupal_json_output(array('form' => $replace));
  drupal_exit();
}
/**
 * Menu callback: Watch chat
 */
function chatroom_livesupport_watch_chatroom($form, &$form_state, $cid = 0) {
  $form['filter'] = array(
    '#type' => 'fieldset',
    '#title' => t('Filter'),
    '#collapsible' => TRUE,
    '#collapsed' => TRUE
  );
  $form['filter']['name'] = array(
    '#type' => 'textfield',
    '#title' => t('Operator Name'),
    '#size' => 20,
    '#autocomplete_path' => 'user/autocomplete',
    '#default_value' => !empty($_SESSION['chatroom_livesupport_watch_filter']['name']) ? $_SESSION['chatroom_livesupport_watch_filter']['name'] : '',
    '#description' => t('Enter operator name')
  );

  $form['filter']['modified'] = array(
    '#type' => 'date_popup',
    '#date_timezone' => date_default_timezone(),
    '#date_format' => 'd-m-Y',
    '#date_year_range' => '-3:+0',
    '#title' => t('Datetime'),
    '#default_value' => !empty($_SESSION['chatroom_livesupport_watch_filter']['modified'])
      ? $_SESSION['chatroom_livesupport_watch_filter']['modified'] : '',
  );
  $form['filter']['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Submit'),
    '#submit' => array('chatroom_livesupport_watch_chatroom_form_submit')
  );
  $form['filter']['reset'] = array(
    '#type' => 'submit',
    '#value' => t('Reset'),
    '#submit' => array('chatroom_livesupport_watch_chatroom_form_submit')
  );

  // Load chatroom info
  $chatroom = new ChatroomLivesupport($cid);

  $query = db_select('chatroom_msg', 'cm')
    ->fields('cm')
    ->condition('cid', $cid);
  // Merge filter into query
  if (!empty($_SESSION['chatroom_livesupport_watch_filter']['modified'])) {
    $modified = $_SESSION['chatroom_livesupport_watch_filter']['modified'];
    $query->condition('modified', strtotime($modified) , '>=');
    $query->condition('modified', strtotime($modified + 86400) , '>');
  }
  if (!empty($_SESSION['chatroom_livesupport_watch_filter']['name'])) {
    $name = $_SESSION['chatroom_livesupport_watch_filter']['name'];
    $account = user_load_by_name($name);
    if ($account->uid != 0) {
      $query->condition('uid', array($chatroom->get('uid'), $account->uid) , 'IN');
    }
  }

  $query = $query->extend('PagerDefault');
  $messages = $query->limit(20)->execute();

  // Output message
  $output = '<div class="chatroom-board" id="chatroom-board-' . $chatroom->get('cid') . '" role="log">';
  foreach ($messages as $message) {
    $output .= theme('chatroom_message', array('message' => $message, 'chatroom' => $chatroom));
  }
  $output .= '</div>';

  $form['text'] = array(
    '#type' => 'markup',
    '#markup' => $output
  );
  $form['pager'] = array('#markup' => theme('pager'));
  return $form;
}

/**
 * Submit handler form for chatroom_livesupport_watch_chatroom
 */

function chatroom_livesupport_watch_chatroom_form_submit($form, &$form_state) {
  $values = $form_state['values'];
  switch($values['op']) {
    case t('Filter'):
      if (!empty($values['name'])) {
        $account = user_load_by_name($values['name']);
        if ($account) {
          $_SESSION['chatroom_livesupport_watch_filter']['name'] = $values['name'];
        }
      }
      if (!empty($values['modified'])) {
        $_SESSION['chatroom_livesupport_watch_filter']['modified'] = $values['modified'];
      }
      break;
    case t('Reset'):
      $_SESSION['chatroom_livesupport_watch_filter'] = array('name' => '', 'modified' => '');
      break;
  }
}